package org.edu.modules.stu.stu.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.dto.ExcelPo;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.common.utils.PoiUtils;
import org.edu.modules.stu.common.entity.VeBaseAppUser;
import org.edu.modules.stu.common.service.VeBaseAppUserService;
import org.edu.modules.stu.common.service.VeBaseTeacherService;
import org.edu.modules.stu.stu.dto.VeStuLeaveDto;
import org.edu.common.dto.AllDto;
import org.edu.modules.stu.stu.entity.VeStuLeave;
import org.edu.modules.stu.stu.service.VeStuLeaveService;
import org.edu.common.api.vo.Result;
import org.edu.common.base.PageDto;
import org.edu.common.dto.StatusDto;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Api(tags = {"请假信息表"})
@RestController
@RequestMapping("/stu/veStuLeave")
@Slf4j
public class VeStuLeaveController {

    @Autowired
    private VeStuLeaveService veStuLeaveService;

    @Autowired
    private VeBaseAppUserService veBaseAppUserService;

    @Autowired
    private VeBaseTeacherService veBaseTeacherService;

    @ApiOperation("分页查询请假信息表")
    @PostMapping("/page")
    public Result<?> page(@RequestBody PageDto<VeStuLeave> page) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        IPage<VeStuLeaveDto> pageDto = null;
        QueryWrapper<VeStuLeave> queryWrapper = page.buildQueryWrapper(VeStuLeave.class);
        if (appUser.getUserType().contains("2")) {
            //如果用户类型是2，为学生账号
            pageDto = veStuLeaveService.pageDtoByUserId(page, queryWrapper, appUser.getUserId());
            return Result.OK(pageDto);
        } else if (appUser.getUserType().contains("1")) {
            //如果用户类型是1，为教师账号
            List<Integer> bjIdsList = veBaseTeacherService.getBjIdsListBySysUserId(appUser.getUserId());
            queryWrapper.eq("is_current",0);
            queryWrapper.in("bj_id",bjIdsList);
            pageDto = veStuLeaveService.pageDto(page, queryWrapper);
            return Result.OK(pageDto);
        } else {
            //管理员
            queryWrapper.eq("is_current",0);
            pageDto = veStuLeaveService.pageDto(page, queryWrapper);
        }
        return Result.OK(pageDto);
    }

    /**
     * 查询所有
     */
    @ApiOperation("查询所有")
    @PostMapping("/all")
    public Result<?> all(@RequestBody AllDto<VeStuLeave> page) {
        QueryWrapper<VeStuLeave> queryWrapper = page.buildQueryWrapper(VeStuLeave.class);
        List<VeStuLeave> list = veStuLeaveService.listByWrapper(queryWrapper);
        return Result.OK(list);
    }

    @ApiOperation("导出数据）")
    @PostMapping("/export")
    public Result<?> export(@RequestBody PageDto<VeStuLeave> page, HttpServletResponse resp) {
        QueryWrapper<VeStuLeave> queryWrapper = page.buildQueryWrapper(VeStuLeave.class);
        List<ExcelPo> list = new ArrayList<>();
        list.add(new ExcelPo("学生id", "stuId"));
        list.add(new ExcelPo("学生姓名", "name"));
        list.add(new ExcelPo("学生学号", "code"));
        list.add(new ExcelPo("专业id", "specId"));
        list.add(new ExcelPo("班级id", "bjId"));
        list.add(new ExcelPo("请假类型;1事假、2病假、3丧假", "type"));
        list.add(new ExcelPo("开始时间", "startTime"));
        list.add(new ExcelPo("结束时间", "endTime"));
        list.add(new ExcelPo("申请时间", "applyTime"));
        list.add(new ExcelPo("审核人", "auditUserId"));
        list.add(new ExcelPo("", "auditUserName"));
        list.add(new ExcelPo("审核状态;0待审核 1通过2未通过", "auditStatus"));
        list.add(new ExcelPo("", "auditTime"));
        list.add(new ExcelPo("未通过原因", "auditReason"));
        list.add(new ExcelPo("请假原因", "content"));
        PoiUtils.downloadFile(resp, veStuLeaveService.page(page, queryWrapper).getRecords(), list);
        return Result.OK();
    }

    @AutoLog(value = "请假信息表-分页列表查询")
    @ApiOperation(value = "请假信息表-分页列表查询", notes = "请假信息表-分页列表查询")
    @PostMapping(value = "/list")
    public Result<?> queryPageList(VeStuLeave entity,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeStuLeave> queryWrapper = QueryGenerator.initQueryWrapper(entity, req.getParameterMap());
        PageDto<VeStuLeave> page = new PageDto<VeStuLeave>(pageNo, pageSize);
        IPage<VeStuLeave> pageList = veStuLeaveService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @AutoLog(value = "通过id查询")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeStuLeave dto = veStuLeaveService.findDtoById(id);
        if (dto == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dto);
    }

    @AutoLog(value = "添加")
    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeStuLeaveDto dto) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        if (appUser.getUserType().contains("2")) {
            //学生自己请假,将学号放入
            dto.setCode(appUser.getUserId());
        }
        veStuLeaveService.insertOrUpdate(dto, true);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeStuLeaveDto dto) {
        veStuLeaveService.insertOrUpdate(dto, false);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        veStuLeaveService.delete(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }


    @AutoLog(value = "更新状态")
    @ApiOperation(value = "更新状态")
    @PostMapping(value = "/updateStatus")
    public Result<?> updateStatus(@RequestBody StatusDto statusDto) {
        UpdateWrapper<VeStuLeave> updateWrapper = new UpdateWrapper<>();
        if (statusDto.getIds() != null && statusDto.getIds().size() > 0) {
            updateWrapper.set("audit_status", statusDto.getStatus());
            updateWrapper.in("id", statusDto.getIds());
            veStuLeaveService.update(updateWrapper);
            return Result.OK("批量更新成功!");
        } else {
            return Result.error("未选择!");
        }
    }


    @AutoLog(value = "审核")
    @ApiOperation(value = "审核")
    @PostMapping(value = "/audit")
    public Result<?> audit(@RequestBody VeStuLeaveDto dto) {
        LambdaUpdateWrapper<VeStuLeave> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(VeStuLeave::getAuditStatus, dto.getAuditStatus());
        updateWrapper.set(VeStuLeave::getAuditTime, new Date());
        updateWrapper.set(VeStuLeave::getAuditReason, dto.getAuditReason());

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        updateWrapper.set(VeStuLeave::getAuditUserId, sysUser.getId());
        updateWrapper.set(VeStuLeave::getAuditUserName, sysUser.getRealname());
        updateWrapper.eq(VeStuLeave::getId, dto.getId());
        veStuLeaveService.update(updateWrapper);
        return Result.OK("审核成功!");
    }


}
